﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Media;
using GitManageFileVersionAvaloniaApp.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace GitManageFileVersionAvaloniaApp.ViewModels
{
    public class ReportDataGrid : DataGrid
    {
        /// <summary>
        /// 标题行高
        /// </summary>
        public GridLength HeaderRowHeight = new GridLength(22, GridUnitType.Pixel);
        /// <summary>
        /// 默认行宽
        /// </summary>
        public double DefaultColumnWidth = 60;
        /// <summary>
        /// 合并列数
        /// </summary>
        public int MergeColumnCount = 2;
        /// <summary>
        /// 是否合并相同数据行
        /// </summary>
        public bool IsMergeDataRow = true;

        public IBrush GridBorderBrush = Brush.Parse("#C4D9F6");
        public IBrush HeaderBackgroundBrush = Brush.Parse("#E2EDFA");
        public IBrush HeaderForegroundBrush = Brush.Parse("#1E395B");
        public IBrush RowBackgroundBrush = Brush.Parse("Transparent");
        public IBrush RowForegroundBrush = Brush.Parse("Black");
        public double HeaderFontSize = 12;
        public DataTable Data { get; set; }
        /// <summary>
        /// 列宽，格式：10,*,*,Auto,10
        /// </summary>
        public string ColumnWidth;

        public int ColunmCount = 0;


        protected override Type StyleKeyOverride { get; } = typeof(DataGrid);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dtData"></param>
        /// <param name="columnWidth">列宽："50,60,Auto,*"</param>列名~ColSpan~RowSpan`列名~ColSpan~RowSpan`列名|列名~ColSpan~RowSpan`列名~ColSpan~RowSpan`列名
        /// <param name="headerData"> 表头信息~`:"行`行~主列"  </param>
        /// <param name="mergeColumnCount"></param>
        /// <param name="frozenColumnCount"></param>
        public ReportDataGrid() : base()
        {
            this.BorderThickness = new Avalonia.Thickness(0, 0, 0, 0);
            this.BorderBrush = GridBorderBrush;
            this.Background = Brush.Parse("White");
            this.GridLinesVisibility = DataGridGridLinesVisibility.All;
            this.AutoGenerateColumns = false;
            this.IsReadOnly = true;
            this.SelectionMode = DataGridSelectionMode.Single;
            this.VerticalGridLinesBrush = BorderBrush;
            this.HorizontalGridLinesBrush = BorderBrush;
            LinearGradientBrush lb = new LinearGradientBrush();
            lb.StartPoint = new RelativePoint(0, 0, RelativeUnit.Absolute);
            lb.EndPoint = new RelativePoint(0, 1, RelativeUnit.Absolute);
            lb.GradientStops.Add(new GradientStop(Color.Parse("#EFF5FB"), 0));
            lb.GradientStops.Add(new GradientStop(Color.Parse("#E2EDFA"), 1));
            HeaderBackgroundBrush = lb;
        }
        /// <summary>
        /// 添加文本列
        /// </summary>
        /// <param name="title">列标题</param>
        /// <param name="propertyName">数据源属性名</param>
        /// <param name="dataGridLength">列宽</param>
        /// <param name="minWidth">最小列宽</param>
        public void AddTextColumn(string title, string propertyName, DataGridLength dataGridLength, double minWidth = 80)
        {
            DataGridTextColumn col;
            col = new DataGridTextColumn
            {
                Header = title,
                FontSize = this.HeaderFontSize,
                FontWeight = FontWeight.Normal,
                FontStyle = FontStyle.Normal
            };
            col.IsReadOnly = true;
            col.CanUserSort = false;
            col.MinWidth = minWidth;
            col.Width = dataGridLength;
            col.Binding = new Binding(propertyName);

            this.Columns.Add(col);
        }

        /// <summary>
        /// 添加Grid列
        /// </summary>
        /// <param name="title">列标题</param>
        /// <param name="propertyName">数据源属性名</param>
        /// <param name="dataGridLength">列宽</param>
        public void AddGridColumn(string titleInfo, string innerGridSoureName, string[] propertyName)
        {

            Grid titleGrid = GetTitleGrid(titleInfo);
            AddGridColumn(titleGrid, innerGridSoureName, propertyName);
        }

        /// <summary>
        /// 添加Grid列
        /// </summary>
        /// <param name="title">列标题</param>
        /// <param name="propertyName">数据源属性名</param>
        /// <param name="dataGridLength">列宽</param>
        public void AddGridColumn(Grid titleGrid, string innerGridSoureName, string[] propertyName)
        {
            DataGridTemplateColumn col = new();
            col.HeaderTemplate = new FuncDataTemplate<object>((model, namescpe) =>
            {
                return titleGrid;
            });
            col.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);


            col.CellTemplate = new FuncDataTemplate<object>((model, namescpe) =>
            {
                DataGrid dataGrid = new();
                dataGrid.VerticalGridLinesBrush = BorderBrush;
                dataGrid.HorizontalGridLinesBrush = BorderBrush;
                dataGrid.Classes.Add("InnerGrid");
                dataGrid.BorderBrush = GridBorderBrush;
                dataGrid.GridLinesVisibility = DataGridGridLinesVisibility.All;
                dataGrid.SelectionMode = DataGridSelectionMode.Single;
                dataGrid.Background = Brush.Parse("White");
                if (!string.IsNullOrEmpty(innerGridSoureName))
                    dataGrid.ItemsSource = (System.Collections.IEnumerable)model.GetValueByPropertyName(innerGridSoureName);
                dataGrid.HeadersVisibility = DataGridHeadersVisibility.None;
                for (int i = 0; i < propertyName.Length; i++)
                {
                    DataGridTextColumn innerCol = new();
                    innerCol.IsReadOnly = true;
                    GridLength gl = titleGrid.ColumnDefinitions[i].Width;
                    innerCol.Binding = new Binding(propertyName[i]);

                    DataGridLength dgl = new DataGridLength(gl.Value, DataGridLengthUnitType.Pixel);
                    innerCol.Width = dgl;
                   
                    dataGrid.Columns.Add(innerCol);
                }
                return dataGrid;
            });
            this.Columns.Add(col);
        }
        /// <summary>
        /// 根据样式字符串获取Grid
        /// </summary>
        /// <param name="titleInfos">Title~ColIndex~RowIndex~ColSpan~RowSpan`Title~ColIndex~RowIndex~ColSpan~RowSpan|Title~ColIndex~RowIndex~ColSpan~RowSpan`Title~ColIndex~RowIndex~ColSpan~RowSpan</param>
        /// <returns></returns>
        public Grid GetTitleGrid(string titleInfos)
        {
            titleInfos = titleInfos.Replace("\r\n", "").Replace("\n", "").Trim();
            TitleInfo titleInfo = new TitleInfo();
            //Title~ColIndex~RowIndex~ColSpan~RowSpan~ColWidth`Title~ColIndex~RowIndex~ColSpan~RowSpan~ColWidth|Title~ColIndex~RowIndex~ColSpan~RowSpan`Title~ColIndex~RowIndex~ColSpan~RowSpan
            string[] rowInfos = titleInfos.Split("|");
            TitleRowInfo oRow;
            for (int i = 0; i < rowInfos.Length; i++)
            {
                oRow = new TitleRowInfo();
                string[] colInfos = rowInfos[i].Replace("\r\n", "").Replace("\n", "").Trim().Split("`");
                TitleColumnInfo oCol;
                for (int j = 0; j < colInfos.Length; j++)
                {
                    oCol = new TitleColumnInfo();
                    string[] colDetial = colInfos[j].Replace("\r\n", "").Replace("\n", "").Trim().Split("~");
                    oCol.Title = colDetial[0].Replace("\r\n", "").Replace("\n", "").Trim();
                    oCol.ColIndex = int.Parse(colDetial[1]);
                    oCol.RowIndex = int.Parse(colDetial[2]);
                    try
                    {
                        oCol.ColSpan = int.Parse(colDetial[3]);
                    }
                    catch (Exception)
                    {
                        oCol.ColSpan = 1;
                    }
                    try
                    {
                        oCol.RowSpan = int.Parse(colDetial[4]);
                    }
                    catch (Exception)
                    {
                        oCol.RowSpan = 1;
                    }
                    if (colDetial.Length > 5)
                    {
                        oCol.Width = Convert.ToDouble(colDetial[5]);
                    }
                    oRow.TitleColumns.Add(oCol);
                }
                titleInfo.TitleRows.Add(oRow);
            }
            return GetTitleGrid(titleInfo);
        }
        /// <summary>
        /// 根据样式字符串获取Grid
        /// </summary>
        /// <param name="titleInfos">Title~ColIndex~RowIndex~ColSpan~RowSpan`Title~ColIndex~RowIndex~ColSpan~RowSpan|Title~ColIndex~RowIndex~ColSpan~RowSpan`Title~ColIndex~RowIndex~ColSpan~RowSpan</param>
        /// <returns></returns>
        public Grid GetTitleGrid(TitleInfo titleInfo)
        {
            Grid titleGrid = new Grid();
            #region 用最后一行数据定义列
            int rowCount = titleInfo.TitleRows.Count();
            TitleRowInfo lastRow = titleInfo.TitleRows[rowCount - 1];
            ColumnDefinition col;
            foreach (var colInfo in lastRow.TitleColumns)
            {
                col = new ColumnDefinition(colInfo.Width, GridUnitType.Pixel);
                titleGrid.ColumnDefinitions.Add(col);
            }
            #endregion

            #region 增加行定义
            RowDefinition row;
            foreach (var rowInfo in titleInfo.TitleRows)
            {
                row = new RowDefinition(HeaderRowHeight);
                titleGrid.RowDefinitions.Add(row);
            }
            #endregion

            #region 增加各个单元格
            TextBlock text;
            for (int rowIndex = 0; rowIndex < titleInfo.TitleRows.Count; rowIndex++)
            {
                for (int colIndex = 0; colIndex < titleInfo.TitleRows[rowIndex].TitleColumns.Count; colIndex++)
                {
                    TitleColumnInfo colInfo = titleInfo.TitleRows[rowIndex].TitleColumns[colIndex];
                    if (string.IsNullOrEmpty(colInfo.Title))
                        continue;
                    Border bd = new Border();
                    bd.BorderThickness = new Thickness(0, 0, 1, 1);
                    bd.BorderBrush = GridBorderBrush;
                    bd.Background = HeaderBackgroundBrush;
                    text = new TextBlock();
                    text.Text = colInfo.Title;
                    text.FontWeight = FontWeight.Normal;
                    text.HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center;
                    text.VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center;
                    text.Foreground = HeaderForegroundBrush;
                    text.Background = Brush.Parse("Transparent");
                    text.FontSize = HeaderFontSize;
                    bd.Child = text;
                    titleGrid.Children.Add(bd);
                    Grid.SetColumn(bd, colInfo.ColIndex);
                    Grid.SetRow(bd, colInfo.RowIndex);
                    Grid.SetColumnSpan(bd, colInfo.ColSpan);
                    Grid.SetRowSpan(bd, colInfo.RowSpan);
                }
            }
            #endregion
            return titleGrid;
        }
    }

    public class TitleInfo
    {
        public List<TitleRowInfo> TitleRows = new();
    }
    public class TitleRowInfo
    {
        public List<TitleColumnInfo> TitleColumns = new();
    }
    public class TitleColumnInfo
    {
        public string Title;
        public int RowIndex;
        public int ColIndex;
        public int RowSpan;
        public int ColSpan;
        public Color BGColor;
        public Color ForeColor;
        public double Width;
        public string DataFiled;

    }

}
